/*
 * Created on 07.12.2012
 *
 */
package de.denniswilmsmann.jmslogger.activemq;

import java.util.Random;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import de.svenjacobs.loremipsum.LoremIpsum;

/*
 * $Log: $
 */

public class Producer implements Runnable {

    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    private static String subject = "TestTopic";
    private final MessageProducer producer;
    private final Session session;
    private final Connection connection;
    private final LoremIpsum loremIpsum;
    private final String name;

    public Producer(String name) throws JMSException {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(subject);
        producer = session.createProducer(topic);

        loremIpsum = new LoremIpsum();
        this.name = name;
    }

    public void destroy() {
        try {
            producer.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void produceMessage(String messageText) throws JMSException {
        ObjectMessage oMessage = session.createObjectMessage(new MyMessage(messageText));
        producer.send(oMessage);
        System.out.println(name + " has sent message '" + messageText + "'");
    }

    public void produceRandomMessage() throws JMSException {
        Random rnd = new Random();
        produceMessage(loremIpsum.getWords(rnd.nextInt(127) + 1));
    }

    @Override
    public void run() {
        boolean run = true;
        while (run) {
            try {
                produceRandomMessage();

                Random rnd = new Random();
                int sleep = rnd.nextInt(10) + 1;
                Thread.sleep(sleep * 1000L);

                if (sleep > 7) {
                    run = false;
                }

            } catch (JMSException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.out.println("producer " + name + " has finished");

        destroy();
    }
}
